package com.sky.controller.user;

import com.sky.pojo.AddressBook;
import com.sky.result.Result;
import com.sky.service.user.AddressBookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController()
@RequestMapping("/user/addressBook")
@Api(tags = "用户地址相关接口")
@Slf4j
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;

    /**
     * 查询用户所有地址
     * @return
     */
    @GetMapping("list")
    @ApiOperation("查询用户所有地址")
    public Result<List<AddressBook>> getAllAddress(){
        List<AddressBook> list= addressBookService.getAllAddress();
        return Result.success(list);
    }

    /**
     * 新增地址
     *
     * @param addressBook
     * @return
     */
    @PostMapping
    @ApiOperation("新增地址")
    public Result save(@RequestBody AddressBook addressBook) {
        addressBookService.save(addressBook);
        return Result.success();
    }


    /**
     * 根据用户id查询地址
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation("根据用户id查询地址")
    public Result<AddressBook> getAddressById(@PathVariable Long id){
        AddressBook addressBook=addressBookService.getAddressById(id);
        return Result.success(addressBook);
    }


    /**
     * 根据用户id修改地址
     * @param addressBook
     * @return
     */
    @PutMapping()
    @ApiOperation("根据用户id修改地址")
    public Result<String> updateAddressById(@RequestBody AddressBook addressBook){
        addressBookService.updateAddressById(addressBook);
        return Result.success();
    }


    @PutMapping("/default")
    @ApiOperation("设置默认地址")
    public Result<String> setDefaultAddress(@RequestBody AddressBook addressBook){
        addressBookService.setDefaultAddress(addressBook);
        return Result.success();
    }

    /**
     * 根据id删除地址
     *
     * @param id
     * @return
     */
    @DeleteMapping
    @ApiOperation("根据id删除地址")
    public Result deleteById(Long id) {
        addressBookService.deleteById(id);
        return Result.success();
    }

    /**
     * 查询默认地址
     * @return
     */
    @GetMapping("/default")
    @ApiOperation("查询默认地址")
    public Result<AddressBook> getDefaultAddress(){

        AddressBook addressBook=addressBookService.getDefaultAddress();
        if (addressBook!=null){
            return Result.success(addressBook);
        }
        return Result.error("无默认地址");

    }

}
